﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.Core.Repositories;
using MvcEngine.Core.Base;
using MvcEngine.Core;
using MvcEngine.Core.Extensions;
using MvcEngine.Core.Pagination;

namespace MvcEngine.LinqToSqlProvider
{
    public class BaseRepository<TEntity> : Repository, IBaseRepository<TEntity>
        where TEntity : class, IUnique, new()
    {
        public TEntity Get(Guid id)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.GetTable<TEntity>().Single(t => ((IUnique)t).Id == id && ((IUnique)t).SiteId == SiteContext.Current.Site.Id);
            }
        }

        public IPagination<TEntity> GetAll(int pageIndex, int count)
        {
            using (var contextManager = CreateContextManager(true))
            {
                return contextManager.Context.GetTable<TEntity>().Where(t => ((IUnique)t).SiteId == SiteContext.Current.Site.Id).GetPage(pageIndex, count);
            }
        }

        public void Delete(Guid id)
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.GetTable<TEntity>().DeleteOnSubmit(Get(id));
                contextManager.Commit();
            }
        }

        public void DeleteAll()
        {
            using (var contextManager = CreateContextManager(false))
            {
                contextManager.Context.GetTable<TEntity>().DeleteAllOnSubmit(GetAll(0, 0));
                contextManager.Commit();
            }
        }
    }
}
